package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.service.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    RedisService redisService;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @GetMapping("/getCode")
    public ResultVO<Object> getCode() throws IOException {
        String text = defaultKaptcha.createText();
        String[] textsplit = text.split("@");
        String uuid = IdUtil.simpleUUID();
        String key = CommonConstant.CODE_REDIS_KEY_PREFIX + uuid;
        redisService.setex(key,textsplit[1],5, TimeUnit.MINUTES);

        BufferedImage image = defaultKaptcha.createImage(textsplit[0]);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String encode = Base64.encode(outputStream.toByteArray());
        CodeVO codeVO = new CodeVO(uuid,"data:image/png;base64," + encode);
        return ResultVO.success(codeVO);
    }



}
